package com.yuncheng.spcyApi.partyService;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.PartyRsXxzl;
import com.yuncheng.spcyApi.entity.SpcySqsxWjjl;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.IPartyRsXxzlService;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxWjjlService;
import com.yuncheng.spcyApi.spcyService.ZdyUploadFileService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 党建学习资料
 */
@Component(value = "partyXxzlService")
public class PartyXxzlService {
    private static final Logger log = LoggerFactory.getLogger(PartyXxzlService.class);

    @Resource
    @Lazy
    private IPartyRsXxzlService partyRsXxzlService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private ZdyUploadFileService zdyUploadFileService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    /**
     * 查询学习资料-分页列表
     */
    public HttpResult queryXxzlPageList(PartyRsXxzl xxzl, Integer pageNo, Integer pageSize, OrderItemVo orderItemVo){
        Page<PartyRsXxzl> page = new Page<>(pageNo,pageSize);

        LambdaQueryWrapper<PartyRsXxzl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(xxzl.getFzllx()), PartyRsXxzl::getFzllx, xxzl.getFzllx());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFbt()), PartyRsXxzl::getFbt, xxzl.getFbt());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFfbr()), PartyRsXxzl::getFfbr, xxzl.getFfbr());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFfbzt()), PartyRsXxzl::getFfbzt, xxzl.getFfbzt());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFzy()), PartyRsXxzl::getFzy, xxzl.getFzy());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFzyly()), PartyRsXxzl::getFzyly, xxzl.getFzyly());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFhyzt()), PartyRsXxzl::getFhyzt, xxzl.getFhyzt());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFwczt()), PartyRsXxzl::getFwczt, xxzl.getFwczt());
        queryWrapper.like(StringUtils.isNotBlank(xxzl.getFssdzb()), PartyRsXxzl::getFssdzb, xxzl.getFssdzb());

        if (StringUtils.isBlank(orderItemVo.getOrderItem())) {
            queryWrapper.orderByDesc(PartyRsXxzl::getFfbsj);
            queryWrapper.orderByDesc(PartyRsXxzl::getCreateTime);
        }else {
            OrderItemUtils.setOrderItem(queryWrapper, orderItemVo);
        }
        IPage<PartyRsXxzl> pageList = partyRsXxzlService.page(page, queryWrapper);

        return HttpResult.ok(pageList);
    }

    /**
     * 添加学习资料
     * @param xxzl
     * @return
     */
    public PartyRsXxzl addXxzl(PartyRsXxzl xxzl){
        if (StringUtils.isBlank(xxzl.getFzllx())){
            throw new BusinessException("资料类型参数为空！");
        }

        xxzl.setId(GetUuIdUtils.ReplaceUuId());
        xxzl.setFydcs(0);
        xxzl.setFxzcs(0);

        if (StringUtils.isBlank(xxzl.getFfbsj())) {
            xxzl.setFfbsj(DateConversionUtils.DateToDays(new Date()));
        }

        xxzl.setFfbr(GetCurrentUserUtils.getCurrentUserName());

        if (StringUtils.isNotBlank(xxzl.getFzllx()) && xxzl.getFzllx().equals(SpcyCommonConstant.XXZL_ZLLX_CXDRHD)) {

            if (StringUtils.isBlank(xxzl.getFwczt())) {
                xxzl.setFwczt(SpcyCommonConstant.XXZL_DRHD_WCZT_WKS);
            }

            if (StringUtils.isBlank(xxzl.getFfbzt())){
                xxzl.setFfbzt(SpcyCommonConstant.XXZL_FBZT_YFB);
            }

            if (StringUtils.isBlank(xxzl.getFssdzb())){
                xxzl.setFssdzb(SpcyCommonConstant.XXZL_SSDZB);
            }
        }else {
            xxzl.setFfbzt(SpcyCommonConstant.XXZL_FBZT_CG);
        }

        partyRsXxzlService.save(xxzl);

        String title = "添加"+xxzl.getFzllx()+"学习资料";
        String log = title +": "+ LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(xxzl));
        spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL,log,xxzl.getId(),title,SpcyConstant.LOGS_SYS_TYPE_XZ);

        return xxzl;
    }

    /**
     * 修改学习资料
     * @param buffer  id 学习资料id
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public PartyRsXxzl updateXxzl(HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {
        if (StringUtils.isEmpty(buffer.get("id"))){
            throw new BusinessException("操作失败，数据参数为空！");
        }
        String wjmlId = buffer.get("id");
        PartyRsXxzl updateBean = partyRsXxzlService.getById(wjmlId);
        if (updateBean == null){
            throw new BusinessException("操作失败，没有相匹配的数据！");
        }
        String zllx = updateBean.getFzllx();

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateBean);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateBean, buffer);

        /*if (StringUtils.isBlank(updateBean.getFzllx())){
            throw new BusinessException("资料类型参数为空！");
        }*/

        /*if (StringUtils.isBlank(updateBean.getFfbzt())){
            throw new BusinessException("发布状态为空！");
        }*/

        updateBean.setFzllx(zllx);
        partyRsXxzlService.updateById(updateBean);

        String title = "修改"+updateBean.getFzllx()+"信息";
        String operContent = title +": "+ LogUtils.BeanModifyMsg(updateBean,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL, operContent, updateBean.getId(),title,SpcyConstant.LOGS_SYS_TYPE_XG);

        return updateBean;
    }

    /**
     * 删除学习资料
     * @param id 学习资料id
     */
    public void deleteXxzl(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("删除失败，数据参数为空！");
        }
        PartyRsXxzl xxzl = partyRsXxzlService.getById(id);
        if (xxzl == null){
            throw new BusinessException("没有想匹配的数据！");
        }
        boolean flag = partyRsXxzlService.removeById(id);
        if (flag) {
            zdyUploadFileService.deleteFileByBatch(id);

            String title = "删除"+xxzl.getFzllx()+"信息";
            String operContent = title +": "+ LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(xxzl));
            spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL, operContent, xxzl.getId(), title, SpcyConstant.LOGS_SYS_TYPE_SC);
        }else {
            throw new BusinessException("删除失败，请重试或联系管理员！");
        }
    }

    /**
     * 发布学习资料
     */
    public void releaseXXzl(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("操作失败，数据参数为空！");
        }

        PartyRsXxzl xxzl = partyRsXxzlService.getById(id);
        if (xxzl == null){
            throw new BusinessException("没有想匹配的数据！");
        }
        String oldfbzt = xxzl.getFfbzt();
        xxzl.setFfbsj(DateConversionUtils.DateToDays(new Date()));
        xxzl.setFfbzt(SpcyCommonConstant.XXZL_FBZT_YFB);
        partyRsXxzlService.updateById(xxzl);

        String title = "发布"+xxzl.getFzllx()+"学习资料";
        String log = title + ": "+"标题["+xxzl.getFbt()+"];";
        log += "状态["+oldfbzt+"]";
        spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL,log,id,title,SpcyConstant.LOGS_SYS_TYPE_BC);
    }

    /**
     * 下架学习资料
     */
    public void xjXxzl(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("操作失败，数据参数为空！");
        }
        PartyRsXxzl xxzl = partyRsXxzlService.getById(id);
        if (xxzl == null){
            throw new BusinessException("没有想匹配的数据！");
        }
        xxzl.setFfbzt(SpcyCommonConstant.XXZL_FBZT_YXZ);
        partyRsXxzlService.updateById(xxzl);

        String title = "下架"+xxzl.getFzllx()+"学习资料";
        String log = title + ": "+"标题["+xxzl.getFbt()+"];";
        spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL,log,id,title,SpcyConstant.LOGS_SYS_TYPE_BC);
    }

    /**
     * 获取学习资料-根据id
     */
    public PartyRsXxzl queryXxzlById(String id){
        return partyRsXxzlService.getById(id);
    }

    /**
     * 获取学习资料详情
     */
    public Map queryXxzlXq(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("数据参数为空！");
        }

        Map result = new HashMap();

        PartyRsXxzl xxzl = queryXxzlById(id);
        updateXxzlYdcs(xxzl, id);

        result.put("xxzl", xxzl);
        result.put("fjList", queryXxzlFileRecords(id));
        return result;
    }

    /**
     * 计算学习资料-下载次数
     */
    public void updateXxzlXzcs(String id){
        if (StringUtils.isBlank(id)){
            return;
        }

        PartyRsXxzl xxzl = queryXxzlById(id);
        if (xxzl != null){
            Integer fxzcs = xxzl.getFxzcs();
            xxzl.setFxzcs(fxzcs+1);
            partyRsXxzlService.updateById(xxzl);
        }
    }

    /**
     * 计算学习资料-阅读次数
     */
    public void updateXxzlYdcs(PartyRsXxzl xxzl, String id){
        if (StringUtils.isBlank(id)){
            log.error("计算学习资料-阅读次数出错：id参数为空！");
            return;
        }

        if (xxzl == null) {
            xxzl = queryXxzlById(id);
        }

        if (xxzl != null){
            Integer fydcs = xxzl.getFydcs();
            xxzl.setFydcs(fydcs+1);
            partyRsXxzlService.updateById(xxzl);
        }
    }

    /**
     * 党日活动-提交
     */
    public void drhdSubmit(PartyRsXxzl xxzl, HashMap<String, String> buffer) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        if (StringUtils.isBlank(xxzl.getId())){
            xxzl.setFwczt(SpcyCommonConstant.XXZL_DRHD_WCZT_YWC);
            xxzl.setFfbzt(SpcyCommonConstant.XXZL_FBZT_YFB);
            addXxzl(xxzl);
        }else {

            PartyRsXxzl updateBean = queryXxzlById(xxzl.getId());
            if (updateBean == null) {
                throw new BusinessException("没有相匹配的活动数据！");
            }

            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateBean);
            ConvertUtils.register(new DateConvert(), java.util.Date.class);
            // 自动完成页面到bean的数据对接
            BeanUtils.populate(updateBean, buffer);

            if (StringUtils.isBlank(updateBean.getFwcsj())) {
                updateBean.setFwcsj(DateConversionUtils.DateToStringYYYYMMDD(new Date()));
            }
            if (StringUtils.isBlank(updateBean.getFfbsj())) {
                updateBean.setFfbsj(DateConversionUtils.DateToDays(new Date()));
            }
            updateBean.setFwczt(SpcyCommonConstant.XXZL_DRHD_WCZT_YWC);
            updateBean.setFfbzt(SpcyCommonConstant.XXZL_FBZT_YFB);
            partyRsXxzlService.updateById(updateBean);

            String title = "提交" + updateBean.getFzllx() + "信息";
            String operContent = title + ": " + LogUtils.BeanModifyMsg(updateBean, oldMap);

            spcyLogService.addLogs(LogConstant.LOGS_PARTY_XXZL, operContent, updateBean.getId(), title, SpcyConstant.LOGS_SYS_TYPE_XG);
        }
    }

    /**
     * 党建学习-附件分类-ppt/视频/pdf/mp3
     */
    public Map queryDjxxTypeFjList(String id){
        List<SpcySqsxWjjl> fjList = queryXxzlFileRecords(id);

        List<SpcySqsxWjjl> videoList = new ArrayList<>();
        List<SpcySqsxWjjl> mp3List = new ArrayList<>();
        List<SpcySqsxWjjl> pdfList = new ArrayList<>();
        List<SpcySqsxWjjl> pptList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(fjList)){

            videoList = fjList.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFwjlx()) && f.getFwjlx().equals(".mp4"))
                    .collect(Collectors.toList());

            mp3List = fjList.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFwjlx()) && f.getFwjlx().equals(".mp3"))
                    .collect(Collectors.toList());

            pdfList = fjList.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFwjlx()) && f.getFwjlx().equals(".pdf"))
                    .collect(Collectors.toList());

            pptList = fjList.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFwjlx()) && (f.getFwjlx().equals(".ppt") || f.getFwjlx().equals(".pptx")))
                    .collect(Collectors.toList());
        }

        Map result = new HashMap();
        result.put("videoList", videoList);
        result.put("mp3List", mp3List);
        result.put("pptList", pptList);
        result.put("pdfList", pdfList);

        return result;
    }

    /**
     * 获取对应学习资料的附件记录
     * @param id 学习资料id
     */
    public List<SpcySqsxWjjl> queryXxzlFileRecords(String id){
        return zdyUploadFileService.queryWjjlByPid(id);
    }

    /**
     * 上传文件
     * @param uploadFile
     * @param fpid 业务id
     * @param type 资料类型
     */
    public void uploadFile(MultipartFile[] uploadFile,String fpid,String type){
        zdyUploadFileService.uploadFile(uploadFile, fpid, type, SpcyConstant.PARTY_XXZL_WJJL_FILE_BASE_URL+"/"+DateConversionUtils.DateToMonth(new Date()));
    }

    /**
     * 删除文件
     * @param id
     */
    public void deleteFile(String id){
        zdyUploadFileService.deleteFile(id, null);
    }

    /**
     * 下载文件
     * @param fileId 文件id
     * @param response
     */
    public void downFile(String fileId, HttpServletResponse response){
        SpcySqsxWjjl wjjl = zdyUploadFileService.queryWjjlById(fileId);
        if (wjjl != null && StringUtils.isNotBlank(wjjl.getFwjlx())
                && (wjjl.getFwjlx().equals(".pdf") || wjjl.getFwjlx().equals(".mp3") || wjjl.getFwjlx().equals(".mp4"))){
            updateXxzlYdcs(null, wjjl.getFpid());
        }
        updateXxzlXzcs(wjjl.getFpid());
        zdyUploadFileService.downloadFile(wjjl, response);
    }






}
